import { BASE_URL } from '@/configs/env'
import message from '@/utils/message'
import i18n from '@/i18n'

const getToken = (): string | null => {
  // return process.env.NODE_ENV === 'development'
  //   ? STATIC_TOKEN
  //   : `Bearer ${localStorage.getItem('token')}`
  return `Bearer ${localStorage.getItem('token')}`
}

const getHeaders = (): HeadersInit => {
  return {
    'Content-Type': 'application/json',
    Authorization: getToken(),
  }
}

const handleResponse = async <T>(response: Response): Promise<T> => {
  const data = await response.json()
  if (!response.ok || data.code !== 200) {
    const error = new Error(data.msg || '请求失败')

    if (data.code === 401) {
      error.name = 'UnauthorizedError'
      message.error('登录状态已过期')
    }
    else if (data.code === 601) {
      message.warning(i18n.global.t('investment.tip_import'))
    }
    else {
      message.error(data.msg || '未知错误,请联系管理员')
    }

    throw error
  }
  return data
}

const handleError = (error: Error): never => {
  console.error('API 请求失败:', error)
  message.error(error + '')
  throw error
}

const get = async <T>(endpoint: string, params: Record<string, string> = {}): Promise<T> => {
  const url = new URL(`${BASE_URL}${endpoint}`)
  Object.keys(params).forEach((key) => url.searchParams.append(key, params[key]))

  try {
    const response = await fetch(url.toString(), {
      method: 'GET',
      headers: getHeaders(),
    })
    return handleResponse<T>(response)
  }
  catch (error) {
    return handleError(error as Error)
  }
}

const post = async <T>(endpoint: string, body: Record<string, any> = {}): Promise<T> => {
  try {
    const response = await fetch(`${BASE_URL}${endpoint}`, {
      method: 'POST',
      headers: getHeaders(),
      body: JSON.stringify(body),
      // 'Content-Type': file ? 'multipart/form-data' : 'application/json',
    })
    return handleResponse<T>(response)
  }
  catch (error) {
    return handleError(error as Error)
  }
}
const uploadFile = async <T>(endpoint: string, file: File, downFile?: File): Promise<T> => {
  try {
    const formData = new FormData()
    formData.append('file', file)
    downFile && formData.append('downFile', downFile)
    const response = await fetch(`${BASE_URL}${endpoint}`, {
      method: 'POST',
      headers: {
        Authorization: getToken(),
      },
      body: formData,
    })

    return handleResponse<T>(response)
  }
  catch (error) {
    return handleError(error as Error)
  }
}
const put = async <T>(endpoint: string, body: Record<string, any> = {}): Promise<T> => {
  try {
    const response = await fetch(`${BASE_URL}${endpoint}`, {
      method: 'PUT',
      headers: getHeaders(),

      body: JSON.stringify(body),
    })
    return handleResponse<T>(response)
  }
  catch (error) {
    return handleError(error as Error)
  }
}

const del = async <T>(endpoint: string): Promise<T> => {
  try {
    const response = await fetch(`${BASE_URL}${endpoint}`, {
      method: 'DELETE',
      headers: getHeaders(),
    })
    return handleResponse<T>(response)
  }
  catch (error) {
    return handleError(error as Error)
  }
}

const streamDialogue = async (data) => {
  try {
    const response = await fetch(`${BASE_URL}/system/chat/completion-messages`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: getToken(),
      },
      body: JSON.stringify({ query: data }),
    })
    return response.body
  }
  catch (error) {
    console.error('请求AI接口出现错误:', error)
    throw error
  }
}

export default {
  get,
  post,
  put,
  del,
  uploadFile,
  streamDialogue,
}
